package com.example.aigc_education.integration.threeparty;

import com.example.aigc_education.common.BusinessException;
import com.example.aigc_education.constant.HttpStatus;
import com.example.aigc_education.domain.request.ChatAiContentRequest;
import com.example.aigc_education.domain.vo.FilePathVO;
import com.example.aigc_education.integration.ChatGLMFileIntegration;
import com.example.aigc_education.integration.request.ChatMessageRequest;
import com.example.aigc_education.utils.ResultUtil;
import com.example.aigc_education.utils.SecurityUtils;
import com.example.aigc_education.utils.UUID;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.annotation.Resource;
import java.util.Optional;

@Service
public class ChatglmService {

    @Resource
    private ChatGLMFileIntegration chatGLMFileIntegration;

    /**
     * 组合类，耦合，需剔除
     */
    @Resource
    private AliYunService aliYunService;


    /**
     * ocr识别结果，封装为ChatAiContentRequest
     */
    public ChatAiContentRequest ocrContentRequest(MultipartFile file){
        ResultUtil resultUtil = aliYunService.uploadDocument(file);
        String code = resultUtil.get("code") + "";
        if ("500".equals(code)){
            throw new BusinessException((String) resultUtil.get("msg"));
        }
        FilePathVO data = (FilePathVO) resultUtil.get("data");
        // todo:存至File表
        String localTmpPath = data.getLocalTmpPath();

        String fileId = chatGLMFileIntegration.uploadFile(localTmpPath);

        String content = chatGLMFileIntegration.ocrResult(fileId);
        return ChatAiContentRequest.builder().convId(UUID.fastUUID().toString()).content(content).build();
    }

    /**
     * chat
     */
    public ChatMessageRequest chat(ChatAiContentRequest request){
        return chatGLMFileIntegration.chat(request, String.valueOf(SecurityUtils.getUserId()));
    }

    public SseEmitter docChatSse(ChatAiContentRequest request) {
        return chatGLMFileIntegration.docChatSse(request, String.valueOf(SecurityUtils.getUserId()));
    }
}
